const express=require('express')
const app=express()
const bodyParser=require('body-parser')
const mysql=require('mysql')
const axios=require('axios')
const connection = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'ok',
    database:'myapp'
})

app.use(bodyParser.json())
app.use(express.urlencoded({ extended:true }))

//登录
app.get('/get_user',(req,res)=> {
    res.json({
        "username":"admin",
        "password":"123456"
    })
})
//注册
app.post('/add_user',(req,res)=> {
    let { username, password } = req.body
    console.log(req.body)
    res.json({
        code:1,
        msg:'注册成功'
    })
})

//文章列表接口
app.get('/articles',(req,res)=>{
    res.json([
            {"id":"1","title":"文章标题一","content":"文章内容一"},
            {"id":"2","title":"文章标题二","content":"文章内容二"},
            {"id":"3","title":"文章标题三","content":"文章内容三"},
            {"id":"4","title":"文章标题四","content":"文章内容四"},
          ])
})
//文章内容接口
app.get("/article/:id",(req,res)=>{
    let id =req .params.id
    if(id==1){
        res.json({"id":"1","title":"文章标题一","content":"文章内容一"})
    }else if(id==2){
        res.json({"id":"2","title":"文章标题二","content":"文章内容二"})
    }else if(id==3){
        res.json({"id":"3","title":"文章标题三","content":"文章内容三"})
    }else if(id==4){ 
        res.json({"id":"4","title":"文章标题四","content":"文章内容四"})
    }else{
        res.json({})
    }
})

//微信登录
app.get('/auth/:code',(req,res)=>{
    const code=req.params.code
    res.json({"msg":"微信登录成功，并已于admin账户绑定","token":code})
})
//登录操作
app.post('/zhlogin',(req,res)=>{
    console.log('账号密码登录')
})
app.post('/wxlogin',(req,res)=>{

    const code = req.body.code
    console.log(code)
    axios.get('https://api.weixin.qq.com/sns/jscode2session?appid=wx914bdd07703d939b&secret=340c8309c7df0f0ef66be42fc6473c99&js_code='+code+'&grant_type=authorization_code')
    .then(res=>{
        console.log(res.data)
    })
    console.log('微信登录')
    //微信授权码
    const code = req.body.code
    console.log(code)
    //访问微信登陆接口（微信服务器）
    //获取session_id
    const sessionId='0022xweerrvddfdb2020042710083456'
    //将sessionId存储到redis或mysql中,每次的登陆都要进行校验

    connection.connect()
    var resBody = {}

    let sql='select * as count from `user` where wxcode = ?'
    connection.query(sql,sessionId,(err,result)=>{
        if(result) {

        }
    })

    connection.end()

    

})
app.listen(3000)